﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ScannerApp.Common.Print
{
    public class ComPrintStatus
    {
        private static string strCOMPort;
        private static int intBaud;
        private static int intDataBits;
        private static int intStopBits;
        private static int intParity;

        #region 屬性

        public static string COMPort
        {
            get { return strCOMPort; }
            set { strCOMPort = value; }
        }

        public static int Baud
        {
            get { return intBaud; }
            set { intBaud = value; }
        }

        public static int DataBits
        {
            get { return intDataBits; }
            set { intDataBits = value; }
        }

        public static int StopBits
        {
            get { return intStopBits; }
            set { intStopBits = value; }
        }

        public static int Parity
        {
            get { return intParity; }
            set { intParity = value; }
        }

        #endregion
        /// 锁变量
        /// </summary>
        public static object _lock = new object();
        /// <summary>
        /// 串口资源
        /// </summary>
        private static SerialPort serialPort = null;

        /// <summary>
        /// 向串口发送数据，读取返回数据
        /// </summary>
        /// <param name="sendData">发送的数据</param>
        /// <returns>返回的数据</returns>
        public static string ReadPort(string sendData)
        {
            lock (_lock)
            {
                if (serialPort == null)
                    serialPort = new SerialPort(COMPort, intBaud, System.IO.Ports.Parity.None, intDataBits, System.IO.Ports.StopBits.One);
                serialPort.ReadBufferSize = 1024;
                serialPort.WriteBufferSize = 1024;

                sendData = sendData.Replace(" ", "");//去除16进制数据中所有空格
                sendData = sendData.Replace("\r", "");//去除16进制数据中所有换行
                sendData = sendData.Replace("\n", "");//去除16进制数据中所有换行

                if (sendData.Length == 1)//数据长度为1的时候，在数据前补0
                {
                    sendData = "0" + sendData;
                }
                else if (sendData.Length % 2 != 0)//数据长度为奇数位时，去除最后一位数据
                {
                    sendData = sendData.Remove(sendData.Length - 1, 1);
                }
                List<string> sendData16 = new List<string>();//将发送的数据，2个合为1个，然后放在该缓存里 如:123456→12,34,56
                for (int i = 0; i < sendData.Length; i += 2)
                {
                    sendData16.Add(sendData.Substring(i, 2));
                }
                byte[] sendBuffer = null;//发送数据缓冲区
                sendBuffer = new byte[sendData16.Count];//sendBuffer的长度设置为:发送的数据2合1后的字节数
                for (int i = 0; i < sendData16.Count; i++)
                {
                    sendBuffer[i] = (byte)(Convert.ToInt32(sendData16[i], 16));//发送数据改为16进制
                }
                //打开连接
                if (!serialPort.IsOpen) serialPort.Open();

                //发送数据
                serialPort.Write(sendBuffer, 0, sendBuffer.Length);

                //读取返回数据
                //DateTime dt = DateTime.Now;
                //while (serialPort.BytesToRead < 2)
                //{
                //    Thread.Sleep(1);

                //    if (DateTime.Now.Subtract(dt).TotalMilliseconds > 5000) //如果5秒后仍然无数据返回，则视为超时
                //    {
                //        throw new Exception("主版无响应");
                //    }
                //}
                List<byte> recList = new List<byte>();

                StringBuilder recBuffer16 = new StringBuilder();//定义16进制接收缓存

                Thread.Sleep(50);//发送和接收均为文本时，接收中为加入判断是否为文字的算法，发送你（C4E3），接收可能识别为C4,E3，可用在这里加延时解决

                if (serialPort.BytesToRead > 0)
                {
                    byte[] recData = new byte[serialPort.BytesToRead];
                    serialPort.Read(recData, 0, recData.Length);
                    for (int i = 0; i < recData.Length; i++)
                    {
                        recBuffer16.AppendFormat("{0:X2}" + " ", recData[i]);//X2表示十六进制格式（大写），域宽2位，不足的左边填0。
                    }
                    //recList.AddRange(recData);
                }
                Thread.Sleep(1);


                //关闭连接
                if (serialPort.IsOpen) serialPort.Close();
                if (recBuffer16.ToString().Trim() == "00")
                    return "00";
                else return  recBuffer16.ToString().Trim() ;
            }
        }
        public static string ReadPort_Str(string sendData)
        {
            lock (_lock)
            {
                if (serialPort == null)
                    serialPort = new SerialPort(COMPort, intBaud, System.IO.Ports.Parity.None, intDataBits, System.IO.Ports.StopBits.One);
                serialPort.ReadBufferSize = 1024;
                serialPort.WriteBufferSize = 1024;
                byte[] sendBuffer = null;//发送数据缓冲区
                sendBuffer = System.Text.Encoding.Default.GetBytes(sendData);//转码
                //打开连接
                if (!serialPort.IsOpen) serialPort.Open();

                //发送数据
                serialPort.Write(sendBuffer, 0, sendBuffer.Length);

                //读取返回数据
                //DateTime dt = DateTime.Now;
                //while (serialPort.BytesToRead < 2)
                //{
                //    Thread.Sleep(1);

                //    if (DateTime.Now.Subtract(dt).TotalMilliseconds > 5000) //如果5秒后仍然无数据返回，则视为超时
                //    {
                //        throw new Exception("主版无响应");
                //    }
                //}
                List<byte> recList = new List<byte>();


                string recstr = "";
                Thread.Sleep(10);//发送和接收均为文本时，接收中为加入判断是否为文字的算法，发送你（C4E3），接收可能识别为C4,E3，可用在这里加延时解决

                if (serialPort.BytesToRead > 0)
                {
                    byte[] recData = new byte[serialPort.BytesToRead];
                    serialPort.Read(recData, 0, recData.Length);
                   recstr  = System.Text.Encoding.Default.GetString(recData);//转码 
                }
                Thread.Sleep(1);


                //关闭连接
                if (serialPort.IsOpen) serialPort.Close();
             
                  return recstr;
            }
        }

        public static string test()
        {
          return   Enum.GetName(typeof(PrintStatus),int.Parse("02"));
        }

        public enum PrintStatus
        {
            就绪 = 00,
            卡纸 = 02,
            开盖 = 41,
            开盖且缺纸 = 45,
            开机中 = 11,
            正在打印 = 20,
            缺纸 = 04
        }
    }
}
